package com.bai.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bai.base.exceptionHandler.BaiException;
import com.bai.order.entity.Order;
import com.bai.order.entity.PayLog;
import com.bai.order.mapper.PayLogMapper;
import com.bai.order.service.OrderService;
import com.bai.order.service.PayLogService;
import com.bai.utils.HttpClienWxUtil;
import com.bai.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author bai
 * @since 2023-08-19
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    private OrderService orderService;

    /**
     * 根据订单号生成微信支付二维码
     *
     * @param orderNo
     * @return
     */
    @Override
    public Map creatNative(String orderNo) {
        try {
            //TODO:根据订单号查询订单信息
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);
            Order order = orderService.getOne(queryWrapper);
            //TODO:使用map设置二维码所需的参数
            HashMap map = new HashMap();
            //设置支付参数
            map.put("appid", "wx74862e0dfcf69954");//应用id
            map.put("mch_id", "1558950191");//商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            map.put("body", order.getCourseTitle());//课程名称
            map.put("out_trade_no", orderNo);//订单编号
            map.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue() + "");//交易金额
            map.put("spbill_create_ip", "127.0.0.1");//终端ip
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");//回调地址
            map.put("trade_type", "NATIVE");//交易类型
            // TODO:发生http请求，传递xml格式参数
            HttpClienWxUtil client = new HttpClienWxUtil("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml格式参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行请求发送
            client.post();
            //TODO:得到返回结果
            String xml = client.getContent();
            //xml换为map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            Map hashMap = new HashMap();
            hashMap.put("out_trade_no", orderNo);
            hashMap.put("course_id", order.getCourseId());
            hashMap.put("total_fee", order.getTotalFee());
            hashMap.put("result_code", resultMap.get("result_code"));
            hashMap.put("code_url", resultMap.get("code_url"));
            return hashMap;
        } catch (Exception e) {
            throw new BaiException(2001, "支付异常");
        }
    }

    /**
     * 查询支付状态
     *
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //设置查询参数
            HashMap map = new HashMap();
            map.put("appid", "wx74862e0dfcf69954");//应用id
            map.put("mch_id", "1558950191");//商户号
            map.put("out_trade_no", orderNo);//订单编号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            // TODO:发生http请求，传递xml格式参数
            HttpClienWxUtil client = new HttpClienWxUtil("https://api.mch.weixin.qq.com/pay/orderquery");
            //设置xml格式参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行请求发送
            client.post();
            //TODO:得到返回结果
            String xml = client.getContent();
            //xml换为map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;
        } catch (Exception e) {
            new BaiException();
        }
        return null;
    }

    /**
     * 支付成功向订单表添加记录
     *
     * @param map
     */
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //获取订单号
        String outTradeNo = map.get("out_trade_no");
        //TODO:根据订单号查询订单信息
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", outTradeNo);
        Order order = orderService.getOne(queryWrapper);

        //TODO:更新订单
        if (order.getStatus().intValue() == 1) {
            return;
        }
        order.setStatus(1);
        orderService.updateById(order);

        //向支付表添加支付记录
        PayLog payLog = new PayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);
    }
}
